package aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zhangxuhui
 * @Date 2023/12/21
 * @email zxh_1633@163.com
 * 造成线程安全问题的原因：
 *  可见性：一个线程的修改是否对另一个线程可见
 *  有序性：是否会进行指令重排序
 *  原子性：一个线程执行的时候另一个线程只能阻塞
 */
public class AQSTest {
    //共享变量
    public static Integer count = 0;

    //锁对象
    private static Lock lock = new ReentrantLock();

    //操作
    public static void asc(){
        try {
            Thread.sleep(10);
            lock.lock();
            count++;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
           new Thread(()->{
               asc();
               latch.countDown();
           }).start();
        }
        latch.await();
        System.out.println("AQSTest.count = " + AQSTest.count);
    }

}
